package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ShopMapper shopMapper;

    @Override
    public Result queryShopById(Long id) {
         String key = RedisConstants.CACHE_SHOP_KEY+id;
         //从缓存中查找店铺信息
        String ShopJosn = stringRedisTemplate.opsForValue().get(key);
        //若缓存中找到，则返回店铺信息
        if(StrUtil.isNotBlank(ShopJosn)){
             Shop shop  =JSONUtil.toBean(ShopJosn,Shop.class);
             return Result.ok(shop);
        }
        if(ShopJosn != null){
            return Result.fail("店铺信息为空");
        }
        Shop shop1 =  shopMapper.selectById(id);
        //若数据表中未找到，则返回“店铺不存在”
        if(shop1 == null){
            stringRedisTemplate.opsForValue().set(key,"",2, TimeUnit.MINUTES);
            return Result.fail("该店铺不存在");
        }
        //若数据库中查找到，则将店铺信息存在缓存中后返回结果

            String ShopJosn1 = JSONUtil.toJsonStr(shop1);
            stringRedisTemplate.opsForValue().set(key,ShopJosn1,30,TimeUnit.MINUTES);
            return Result.ok(shop1);



    }
}
